from fastapi import APIRouter, HTTPException, Depends
from typing import List, Dict, Any

from dto.twitter_request import (
    TwitterUrlRequest, 
    TwitterQualityRequest,
    TwitterUsernameRequest
)
from dto.twitter_response import (
    TwitterInfoResponse,
    TwitterDownloadResponse, 
    TwitterMultiQualityResponse,
    TwitterUserTweetsResponse,
    TwitterQualitiesResponse,
    TwitterUrlTypesResponse
)
from service.twitter_downloader_service import TwitterDownloaderService
from config.logging_config import ProjectLoggers

logger = ProjectLoggers.get_service_logger()

# 创建路由器
router = APIRouter(prefix="/twitter", tags=["Twitter"])

# 创建服务实例
twitter_service = TwitterDownloaderService()


@router.post("/info", response_model=TwitterInfoResponse)
async def get_twitter_info(request: TwitterUrlRequest):
    """
    获取Twitter推文详细信息
    
    Args:
        request: Twitter URL请求对象
        
    Returns:
        推文详细信息，包含视频格式列表
    """
    try:
        logger.info(f"获取Twitter推文信息: {request.url}")
        
        result = await twitter_service.get_tweet_info(request.url)
        
        if result["success"]:
            return TwitterInfoResponse(
                success=True,
                data=result["data"]
            )
        else:
            return TwitterInfoResponse(
                success=False,
                error=result["error"]
            )
            
    except Exception as e:
        logger.error(f"获取Twitter推文信息异常: {str(e)}")
        raise HTTPException(status_code=500, detail=f"服务异常: {str(e)}")


@router.post("/download-url", response_model=TwitterDownloadResponse)
async def get_twitter_download_url(request: TwitterQualityRequest):
    """
    获取Twitter视频下载链接
    
    Args:
        request: Twitter质量请求对象（包含URL和质量选项）
        
    Returns:
        指定质量的视频下载链接和相关信息
    """
    try:
        logger.info(f"获取Twitter下载链接: {request.url}, 质量: {request.quality}")
        
        result = await twitter_service.get_download_urls(request.url, request.quality)
        
        if result["success"]:
            return TwitterDownloadResponse(
                success=True,
                data=result["data"]
            )
        else:
            return TwitterDownloadResponse(
                success=False,
                error=result["error"]
            )
            
    except Exception as e:
        logger.error(f"获取Twitter下载链接异常: {str(e)}")
        raise HTTPException(status_code=500, detail=f"服务异常: {str(e)}")


@router.post("/multi-quality-urls", response_model=TwitterMultiQualityResponse)
async def get_twitter_multi_quality_urls(request: TwitterUrlRequest):
    """
    获取Twitter视频多种质量的下载链接
    
    Args:
        request: Twitter URL请求对象
        
    Returns:
        包含多种质量选项的下载链接
    """
    try:
        logger.info(f"获取Twitter多质量下载链接: {request.url}")
        
        result = await twitter_service.get_multiple_quality_urls(request.url)
        
        if result["success"]:
            return TwitterMultiQualityResponse(
                success=True,
                data=result["data"]
            )
        else:
            return TwitterMultiQualityResponse(
                success=False,
                error=result["error"]
            )
            
    except Exception as e:
        logger.error(f"获取Twitter多质量下载链接异常: {str(e)}")
        raise HTTPException(status_code=500, detail=f"服务异常: {str(e)}")


@router.post("/quick-url", response_model=TwitterDownloadResponse)
async def get_twitter_quick_url(request: TwitterUrlRequest):
    """
    快速获取Twitter视频下载链接（最佳质量）
    
    Args:
        request: Twitter URL请求对象
        
    Returns:
        最佳质量的视频下载链接
    """
    try:
        logger.info(f"快速获取Twitter下载链接: {request.url}")
        
        result = await twitter_service.get_download_urls(request.url, "best")
        
        if result["success"]:
            return TwitterDownloadResponse(
                success=True,
                data=result["data"]
            )
        else:
            return TwitterDownloadResponse(
                success=False,
                error=result["error"]
            )
            
    except Exception as e:
        logger.error(f"快速获取Twitter下载链接异常: {str(e)}")
        raise HTTPException(status_code=500, detail=f"服务异常: {str(e)}")


@router.get("/qualities", response_model=TwitterQualitiesResponse)
async def get_twitter_supported_qualities():
    """
    获取支持的视频质量选项
    
    Returns:
        支持的视频质量列表和说明
    """
    try:
        qualities = ["1080p", "720p", "480p", "360p", "240p", "best", "worst"]
        description = (
            "Twitter视频支持的质量选项：\n"
            "- 1080p: 1080p分辨率（如果可用）\n"
            "- 720p: 720p分辨率（如果可用）\n"
            "- 480p: 480p分辨率（如果可用）\n"
            "- 360p: 360p分辨率（如果可用）\n"
            "- 240p: 240p分辨率（如果可用）\n"
            "- best: 最佳质量（推荐）\n"
            "- worst: 最低质量"
        )
        
        return TwitterQualitiesResponse(
            success=True,
            qualities=qualities,
            description=description
        )
        
    except Exception as e:
        logger.error(f"获取Twitter质量选项异常: {str(e)}")
        raise HTTPException(status_code=500, detail=f"服务异常: {str(e)}")


@router.get("/url-types", response_model=TwitterUrlTypesResponse)
async def get_twitter_supported_url_types():
    """
    获取支持的Twitter URL类型
    
    Returns:
        支持的URL类型、示例和说明
    """
    try:
        url_types = [
            "标准推文链接",
            "X.com推文链接", 
            "移动端推文链接",
            "简化推文链接"
        ]
        
        examples = [
            "https://twitter.com/username/status/TWEET_ID",
            "https://x.com/username/status/TWEET_ID",
            "https://mobile.twitter.com/username/status/TWEET_ID", 
            "https://twitter.com/i/web/status/TWEET_ID"
        ]
        
        description = (
            "支持的Twitter/X URL格式：\n"
            "1. 标准推文链接 - twitter.com域名下的推文链接\n"
            "2. X.com推文链接 - 新的x.com域名下的推文链接\n"
            "3. 移动端推文链接 - mobile.twitter.com的移动端链接\n"
            "4. 简化推文链接 - 简化格式的推文链接\n\n"
            "注意：\n"
            "- 只能下载公开推文的视频\n"
            "- 私有账户的推文无法访问\n"
            "- 需要推文包含视频内容"
        )
        
        return TwitterUrlTypesResponse(
            success=True,
            url_types=url_types,
            examples=examples,
            description=description
        )
        
    except Exception as e:
        logger.error(f"获取Twitter URL类型异常: {str(e)}")
        raise HTTPException(status_code=500, detail=f"服务异常: {str(e)}") 